library(optparse)
library(tidyverse)
library(jsonlite)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--config", default = "config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configJson <- fromJSON(opt$config)
qValueCutoff <- configJson$qValueCutoff %>%
  as.numeric()
adjustMethod <- configJson$adjustMethod

data <- read_tsv(opt$i) %>%
  rename(Metabolite = 1)
sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  mutate(ClassNote = as.character(ClassNote))

data1 <- data %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = as.factor(ClassNote))

diff <- data1 %>%
  select_if(is.numeric) %>%
  map_df(~broom::tidy(
    t.test(. ~ ClassNote, data = data1)
  ),
         .id = 'var') %>%
  mutate(p.value = p.adjust(p.value, method = adjustMethod))
diff
write_csv(diff, "test_diff_filter_before.csv")

diff <- diff %>%
  filter(p.value < qValueCutoff)
write_csv(diff, "test_diff.csv")

if (nrow(diff) == 0) {
  stop("EXIT:The data is abnormal, and the filtering result is empty based on the p-value")
}

print(diff$var)

abun.bar <- data1 %>%
  select(c(diff$var, "ClassNote")) %>%
  gather(variable, value, -ClassNote, factor_key = T) %>%
  group_by(variable, ClassNote) %>%
  summarise(Mean = mean(value))
write_csv(abun.bar, "abun.bar.csv")

uniqGroups <- levels(data1$ClassNote)
groupA <- uniqGroups[1]
groupB <- uniqGroups[2]
diff.mean <- diff %>%
  select(c("var", "estimate", "conf.low", "conf.high", "p.value")) %>%
  mutate(ClassNote = ifelse(estimate > 0, groupA, groupB)) %>%
  arrange(desc(estimate)) %>%
  mutate(p.value = signif(p.value, 3))
write_csv(diff.mean, "diff.mean.csv")
